<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Noto Serif SC:300,300italic,400,400italic,700,700italic|Source Code Pro:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"flat"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="原文链接 It’s the perfect pattern match! Pattern matching is one of the most powerful features of any programming language, because it enables you to design rules that match values against each other. Thi">
<meta property="og:type" content="article">
<meta property="og:title" content="Pattern Matching in Swift">
<meta property="og:url" content="http://example.com/2018/12/21/Swift/Pattern%20Matching%20in%20Swift/index.html">
<meta property="og:site_name" content="HR&#39;s Blog">
<meta property="og:description" content="原文链接 It’s the perfect pattern match! Pattern matching is one of the most powerful features of any programming language, because it enables you to design rules that match values against each other. Thi">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2018-12-21T07:12:43.000Z">
<meta property="article:modified_time" content="2018-12-21T07:12:43.000Z">
<meta property="article:author" content="HR">
<meta property="article:tag" content="Ray Wenderlich">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://example.com/2018/12/21/Swift/Pattern%20Matching%20in%20Swift/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'en'
  };
</script>

  <title>Pattern Matching in Swift | HR's Blog</title>
  
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-61905451-1"></script>
    <script>
      if (CONFIG.hostname === location.hostname) {
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'UA-61905451-1');
      }
    </script>






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">HR's Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Swimming 🏊 in the sea🌊of code!</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>About</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>Tags</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>Categories</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="en">
    <link itemprop="mainEntityOfPage" href="http://example.com/2018/12/21/Swift/Pattern%20Matching%20in%20Swift/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="HR">
      <meta itemprop="description" content="Swimming 🏊 in the sea🌊of code!">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="HR's Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Pattern Matching in Swift
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2018-12-21 15:12:43" itemprop="dateCreated datePublished" datetime="2018-12-21T15:12:43+08:00">2018-12-21</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">In</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Swift/" itemprop="url" rel="index"><span itemprop="name">Swift</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p><a target="_blank" rel="noopener" href="https://www.raywenderlich.com/134844/pattern-matching-in-swift">原文链接</a></p>
<p>It’s the perfect pattern match!</p>
<p><em>Pattern matching</em> is one of the most powerful features of any programming language, because it enables you to design rules that match values against each other. This gives you flexibility and simplifies your code.</p>
<p>Apple makes pattern matching available in Swift, and today you’ll explore Swift’s pattern matching techniques.</p>
<span id="more"></span>

<p>The tutorial covers the following patterns:</p>
<ul>
<li><em>Tuple pattern</em></li>
<li><em>Type-casting patterns</em></li>
<li><em>Wildcard pattern</em></li>
<li><em>Optional pattern</em></li>
<li><em>Enumeration case pattern</em></li>
<li><em>Expression pattern</em></li>
</ul>
<p>To show how useful pattern matching can be, in this tutorial you’ll adopt a unique perspective: that of the editor-in-chief at <a target="_blank" rel="noopener" href="https://www.raywenderlich.com/">raywenderlich.com</a>! You’ll use pattern matching to help you schedule and publish tutorials on the site.</p>
<p><em>Note:</em> This tutorial requires Xcode 8 and Swift 3 and assumes you already know the basics of Swift development. If you’re new to Swift, check out some of our other Swift <a target="_blank" rel="noopener" href="https://www.raywenderlich.com/category/swift">tutorials</a> first.</p>
<h2 id="Getting-Started"><a href="#Getting-Started" class="headerlink" title="Getting Started"></a>Getting Started</h2><p>Welcome aboard, temporary editor-in-chief! Your main duties today involve scheduling tutorials for publication on the website. Start by downloading the starter <a target="_blank" rel="noopener" href="https://koenig-media.raywenderlich.com/uploads/2016/07/starter-project.playground-2.zip">playground</a> and open <em>starter project.playground</em> in Xcode.</p>
<p>The playground contains two things:</p>
<ul>
<li>The <code>random_uniform(value:)</code> function, which returns a random number between zero and a certain value. You’ll use this to generate random days for the schedule.</li>
<li>Boilerplate(样板文件) code that parses the <em>tutorials.json</em> file and returns its contents as an array of dictionaries. You’ll use this to extract information about the tutorials you’ll be scheduling.</li>
</ul>
<p><em>Note:</em> To learn more about <em>JSON</em> parsing in Swift, read our <a target="_blank" rel="noopener" href="https://www.raywenderlich.com/120442/swift-json-tutorial">tutorial</a>.</p>
<p>You don’t need to understand how all this works, but you should know the file’s structure, so go ahead and open <em>tutorials.json</em> from the playground’s <em>Resources</em> folder.</p>
<p>Each tutorial post you’ll be scheduling has two properties: title and scheduled day. Your team lead schedules the posts for you, assigning each tutorial a day value between 1 for Monday and 5 for Friday, or <code>nil</code> if leaving the post unscheduled.</p>
<p>You want to publish only one tutorial per day over the course of the week, but when looking over the schedule, you see that your team lead has two tutorials scheduled for the same day. You’ll need to fix the problem. Plus, you want to sort the tutorials in a particular order. How can you do all of that? 查看JSON文件可以看到有些课程安排到了同一天，你要做的是解决这个问题，然后把他们按照特定的顺序排序。</p>
<p>If you guessed “Using patterns!” then you’re on the right track. :]</p>
<h2 id="Pattern-Matching-Types"><a href="#Pattern-Matching-Types" class="headerlink" title="Pattern Matching Types"></a>Pattern Matching Types</h2><p>Let’s get to know the kinds of patterns you’ll be working with in this tutorial.</p>
<ul>
<li><em>Tuple patterns</em> are used to match values of corresponding tuple types.</li>
<li><em>Type-casting patterns</em> allow you to cast or match types.</li>
<li><em>Wildcard patterns</em> match and ignore any kind and type of value.</li>
<li><em>Optional patterns</em> are used to match optional values.</li>
<li><em>Enumeration case patterns</em> match cases of existing enumeration types.</li>
<li><em>Expression patterns</em> allow you to compare a given value against a given expression.</li>
</ul>
<p>You’ll use all of these patterns in your quest to be the best editor-in-chief the site has ever seen!</p>
<h2 id="Tuple-Pattern"><a href="#Tuple-Pattern" class="headerlink" title="Tuple Pattern"></a>Tuple Pattern</h2><p>First, you’ll create a tuple pattern to make an array of tutorials. In the playground, add this code at the end:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">enum</span> <span class="title">Day</span>: <span class="title">Int</span> </span>&#123;</span><br><span class="line">        <span class="keyword">case</span> monday, tuesday, wednesday, thursday, friday, saturday, sunday</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>This creates an enumeration for the days of the week. The underlying raw type is <code>Int</code>, so the days are assigned raw values from 0 for Monday through 6 for Sunday.</p>
<p>Add the following code after the enumeration’s declaration:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Tutorial</span> </span>&#123;</span><br><span class="line">        <span class="keyword">let</span> title: <span class="type">String</span></span><br><span class="line">        <span class="keyword">var</span> day: <span class="type">Day</span>?</span><br><span class="line">        </span><br><span class="line">        <span class="function"><span class="keyword">init</span>(<span class="params">title</span>: <span class="type">String</span>, <span class="params">day</span>: <span class="type">Day</span>? <span class="operator">=</span> <span class="literal">nil</span>)</span> &#123;</span><br><span class="line">                <span class="keyword">self</span>.title <span class="operator">=</span> title</span><br><span class="line">                <span class="keyword">self</span>.day <span class="operator">=</span> day</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Here you define a tutorial type with two properties: the tutorial’s title and scheduled day. <code>day</code> is an optional variable because it can be <code>nil</code> for unscheduled tutorials. 当day没有值的时候意味着这个课程没有安排。</p>
<p>Implement <code>CustomStringConvertible</code> so you can easily print tutorials:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">extension</span> <span class="title">Tutorial</span>: <span class="title">CustomStringConvertible</span> </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> description: <span class="type">String</span> &#123;</span><br><span class="line">                <span class="keyword">var</span> scheduled <span class="operator">=</span> <span class="string">&quot;, not scheduled&quot;</span></span><br><span class="line">                <span class="keyword">if</span> <span class="keyword">let</span> day <span class="operator">=</span> day &#123;</span><br><span class="line">                        scheduled <span class="operator">=</span> <span class="string">&quot;, scheduled on <span class="subst">\(day)</span>&quot;</span></span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">return</span> title <span class="operator">+</span> scheduled</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Now add an array to hold the tutorials:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">var tutorials: [Tutorial] &#x3D; []</span><br></pre></td></tr></table></figure>

<p>Next, convert the array of dictionaries from the starter project to an array of tutorials by adding the following code at the end of the playground:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> dictionary <span class="keyword">in</span> json &#123;</span><br><span class="line">        <span class="keyword">var</span> currentTitle <span class="operator">=</span> <span class="string">&quot;&quot;</span></span><br><span class="line">        <span class="keyword">var</span> currentDay: <span class="type">Day</span>? <span class="operator">=</span> <span class="literal">nil</span></span><br><span class="line">        </span><br><span class="line">        <span class="keyword">for</span> (key, value) <span class="keyword">in</span> dictionary &#123;</span><br><span class="line">                <span class="comment">// todo: extract the information from the dictionary</span></span><br><span class="line">                <span class="comment">// 将Key赋值给currentTitle，将currentDay转换为`Day`赋值给currentDay.</span></span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">let</span> currentTutorial <span class="operator">=</span> <span class="type">Tutorial</span>(title: currentTitle, day: currentDay)</span><br><span class="line">        tutorials.append(currentTutorial)</span><br><span class="line">&#125;  </span><br></pre></td></tr></table></figure>
<p>Here, you iterate over the <code>json</code> array with the <code>for-in</code> statement. For every dictionary in this array, you iterate over the key and value pairs in the dictionary by using a tuple with the <code>for-in</code> statement. This is the <em>tuple pattern</em> in action.</p>
<p>You add each tutorial to the array, but it is currently empty—you are going to set the tutorial’s properties in the next section with the type-casting pattern.</p>
<h2 id="Type-Casting-Patterns"><a href="#Type-Casting-Patterns" class="headerlink" title="Type-Casting Patterns"></a>Type-Casting Patterns</h2><p>利用<code>type-casting patterns</code>将字典转换为<code>Tutorial</code>模型</p>
<p>To extract the tutorial information from the dictionary, you’ll use a type-casting pattern. Add this code inside the <code>for (key, value) in dictionary</code> loop, replacing the placeholder comment:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 1</span></span><br><span class="line"><span class="keyword">switch</span> (key, value) &#123;</span><br><span class="line">        <span class="keyword">case</span> (<span class="string">&quot;title&quot;</span>, <span class="keyword">is</span> <span class="type">String</span>):        <span class="comment">// 2</span></span><br><span class="line">                currentTitle <span class="operator">=</span> value <span class="keyword">as!</span> <span class="type">String</span></span><br><span class="line">        <span class="keyword">case</span> (<span class="string">&quot;day&quot;</span>, <span class="keyword">let</span> dayString <span class="keyword">as</span> <span class="type">String</span>):       <span class="comment">// 3</span></span><br><span class="line">                <span class="keyword">if</span> <span class="keyword">let</span> dayInt <span class="operator">=</span> <span class="type">Int</span>(dayString), <span class="keyword">let</span> day <span class="operator">=</span> <span class="type">Day</span>(rawValue: dayInt <span class="operator">-</span> <span class="number">1</span>) &#123;</span><br><span class="line">                        currentDay <span class="operator">=</span> day</span><br><span class="line">                &#125;</span><br><span class="line">        <span class="keyword">default</span>:           <span class="comment">// 4</span></span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Here’s what’s going on, step by step:</p>
<ol>
<li>You switch on the key and value tuple—the <em>tuple pattern</em> reloaded.</li>
<li>You test if the tutorial’s title is a string with the <em>is type-casting pattern</em> and type-cast it if the test succeeds.</li>
<li>You test if the tutorial’s day is a string with the <em>as type-casting pattern</em>. If the test succeeds, you convert it into an <code>Int</code> first and then into a day of the week with the <code>Day</code> enumeration’s failable initializer <code>init(rawValue:)</code>. You subtract 1 from the <code>dayInt</code> variable because the enumeration’s raw values start at 0, while the days in <em>tutorials.json</em> start at 1.</li>
<li>The <code>switch</code> statement should be exhaustive, so you add a <code>default</code> case. Here you simply exit the switch with the <code>break</code> statement.</li>
</ol>
<p>Add this line of code at the end of the playground to print the array’s content to the console:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">print</span>(tutorials)</span><br></pre></td></tr></table></figure>

<p>As you can see, each tutorial in the array has its corresponding name and scheduled day properly defined now. With everything set up, you’re ready to accomplish your task: schedule only one tutorial per day for the whole week.</p>
<h2 id="Wildcard-Pattern"><a href="#Wildcard-Pattern" class="headerlink" title="Wildcard Pattern"></a>Wildcard Pattern</h2><p>You use the wildcard pattern to schedule the tutorials, but you need to unschedule them all first. Add this line of code at the end of the playground:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">tutorials.forEach &#123; <span class="variable">$0</span>.day <span class="operator">=</span> <span class="literal">nil</span> &#125;</span><br></pre></td></tr></table></figure>

<p>This unschedules all tutorials in the array by setting their day to <code>nil</code>. To schedule the tutorials, add this block of code at the end of the playground:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 1 </span></span><br><span class="line"><span class="keyword">let</span> days <span class="operator">=</span> (<span class="number">0</span><span class="operator">...</span><span class="number">6</span>).map &#123; <span class="type">Day</span>(rawValue: <span class="variable">$0</span>)<span class="operator">!</span> &#125;</span><br><span class="line"><span class="comment">// 2</span></span><br><span class="line"><span class="keyword">let</span> randomDays <span class="operator">=</span> days.sorted &#123; <span class="keyword">_</span> <span class="keyword">in</span> random_uniform(value: <span class="number">2</span>) <span class="operator">==</span> <span class="number">0</span> &#125; <span class="comment">//打乱days的顺序</span></span><br><span class="line"><span class="comment">// 3</span></span><br><span class="line">(<span class="number">0</span><span class="operator">...</span><span class="number">6</span>).forEach &#123; tutorials[<span class="variable">$0</span>].day <span class="operator">=</span> randomDays[<span class="variable">$0</span>] &#125;</span><br></pre></td></tr></table></figure>

<p>There’s a lot going on here, so let’s break it down:</p>
<ol>
<li>First you create an array of days, with every day of the week occurring exactly once.</li>
<li>You “sort” this array. The <code>random_uniform(value:)</code> function is used to randomly determine if an element should be sorted before or after the next element in the array. In the closure, you use an <em>underscore</em> to ignore the closure parameters, since you don’t need them here. Although there are technically <a target="_blank" rel="noopener" href="https://gist.github.com/natecook1000/0ac03efe07f647b46dae">more efficient and mathematically correct ways</a> to randomly shuffle an array this shows the <em>wildcard pattern</em> in action!</li>
<li>Finally, you assign the first seven tutorials the corresponding randomized day of the week.</li>
</ol>
<p>Add this line of code at the end of the playground to print the scheduled tutorials to the console:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">print</span>(tutorials)</span><br></pre></td></tr></table></figure>

<p>Success! You now have one tutorial scheduled for each day of the week, with no doubling up or gaps in the schedule. Great job!</p>
<h2 id="Optional-Pattern"><a href="#Optional-Pattern" class="headerlink" title="Optional Pattern"></a>Optional Pattern</h2><p>The schedule has been conquered, but as editor-in-chief you also need to sort the tutorials. You’ll tackle this with optional patterns.</p>
<p>To sort the <code>tutorials</code> array in ascending order—first the unscheduled tutorials by their title and then the scheduled ones by their day—add the following block of code at the end of the playground:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">tutorials.sort &#123;    <span class="comment">// 1</span></span><br><span class="line">        <span class="keyword">switch</span> (<span class="variable">$0</span>.day, <span class="variable">$1</span>.day) &#123;   <span class="comment">// 2</span></span><br><span class="line">                <span class="keyword">case</span> (<span class="literal">nil</span>, <span class="literal">nil</span>):   <span class="comment">// 3</span></span><br><span class="line">                        <span class="keyword">return</span> <span class="variable">$0</span>.title.compare(<span class="variable">$1</span>.title, options: .caseInsensitive) <span class="operator">==</span> .orderedAscending</span><br><span class="line">                <span class="keyword">case</span> (<span class="keyword">let</span> firstDay<span class="operator">?</span>, <span class="keyword">let</span> secondDay<span class="operator">?</span>):   <span class="comment">// 4</span></span><br><span class="line">                        <span class="keyword">return</span> firstDay.rawValue <span class="comment">// 5</span></span><br><span class="line">                <span class="keyword">case</span> (<span class="literal">nil</span>, <span class="keyword">let</span> secondDay<span class="operator">?</span>):</span><br><span class="line">                        <span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">                <span class="keyword">case</span> (<span class="keyword">let</span> firstDay<span class="operator">?</span>, <span class="literal">nil</span>):</span><br><span class="line">                        <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Here’s what’s going on, step-by-step:</p>
<ol>
<li>You sort the <code>tutorials</code> array with the array’s <code>sort(_:)</code> method. The method’s argument is a trailing closure which defines the sorting order of any two given tutorials in the array. It returns <code>true</code> if you sort the tutorials in ascending order, and <code>false</code> otherwise.</li>
<li>You switch on a tuple made of the days of the two tutorials currently being sorted. This is the <em>tuple pattern</em> in action once more.</li>
<li>If both tutorials are unscheduled, their days are <code>nil</code>, so you sort them in ascending order by their title using the array’s <code>compare(_:options:)</code> method. 如果没有被安排时间则通过他们名字来排序</li>
<li>To test whether both tutorials are scheduled, you use an <em>optional pattern</em>. This pattern will only match a value that can be unwrapped. If both values can be unwrapped, you sort them in ascending order by their raw value.</li>
<li>Again using an optional pattern, you test whether only one of the tutorials is scheduled. If so, you sort the unscheduled one before the scheduled one.</li>
</ol>
<p>Add this line of code at the end of the playground to print the sorted tutorials:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">print</span>(tutorials)</span><br></pre></td></tr></table></figure>

<p>There—now you’ve got those tutorials ordered just how you want them. You’re doing so well at this gig that you deserve a raise! Instead, however … you get more work to do.</p>
<h2 id="Enumeration-Case-Pattern"><a href="#Enumeration-Case-Pattern" class="headerlink" title="Enumeration Case Pattern"></a>Enumeration Case Pattern</h2><p>Now let’s use the enumeration case pattern to determine the scheduled day’s name for each tutorial.</p>
<p>In the extension on <code>Tutorial</code>, you used the enumeration case names from type <code>Day</code> to build your custom string. Instead of remaining tied to these names, add a computed property <code>name</code> to <code>Day</code> by adding the following block of code at the end of the playground:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">extension</span> <span class="title">Day</span> </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> name: <span class="type">String</span> &#123;</span><br><span class="line">                <span class="keyword">switch</span> <span class="keyword">self</span> &#123;</span><br><span class="line">                <span class="keyword">case</span> .monday:</span><br><span class="line">                        <span class="keyword">return</span> <span class="string">&quot;Monday&quot;</span></span><br><span class="line">                <span class="keyword">case</span> .tuesday:</span><br><span class="line">                        <span class="keyword">return</span> <span class="string">&quot;Tuesday&quot;</span></span><br><span class="line">                <span class="keyword">case</span> .wednesday:</span><br><span class="line">                        <span class="keyword">return</span> <span class="string">&quot;Wednesday&quot;</span></span><br><span class="line">                <span class="keyword">case</span> .thursday:</span><br><span class="line">                        <span class="keyword">return</span> <span class="string">&quot;Thursday&quot;</span></span><br><span class="line">                <span class="keyword">case</span> .friday:</span><br><span class="line">                        <span class="keyword">return</span> <span class="string">&quot;Friday&quot;</span></span><br><span class="line">                <span class="keyword">case</span> .saturday:</span><br><span class="line">                        <span class="keyword">return</span> <span class="string">&quot;Saturday&quot;</span></span><br><span class="line">                <span class="keyword">case</span> .sunday:</span><br><span class="line">                        <span class="keyword">return</span> <span class="string">&quot;Sunday&quot;</span></span><br><span class="line">                &#125;</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>The <code>switch</code> statement in this code matches the current value (<code>self</code>) with the possible enumeration cases. This is the <em>enumeration case pattern</em> in action.</p>
<p>Quite impressive, right? Numbers are cool and all, but names are always more intuitive and so much easier to understand after all! :]</p>
<h2 id="Expression-Pattern"><a href="#Expression-Pattern" class="headerlink" title="Expression Pattern"></a>Expression Pattern</h2><p>Next you’ll add a property to describe the tutorials’ scheduling order. You could use the enumeration case pattern again, as follows (<em>don’t add this code to your playground!</em>):</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">var order: String &#123;</span><br><span class="line">        switch self &#123;</span><br><span class="line">        case .monday:</span><br><span class="line">                return &quot;first&quot;</span><br><span class="line">        case .tuesday:</span><br><span class="line">                return &quot;second&quot;</span><br><span class="line">        case .wednesday:</span><br><span class="line">                return &quot;third&quot;</span><br><span class="line">        case .thursday:</span><br><span class="line">                return &quot;fourth&quot;</span><br><span class="line">        case .friday:</span><br><span class="line">                return &quot;fifth&quot;</span><br><span class="line">        case .saturday:</span><br><span class="line">                return &quot;sixth&quot;</span><br><span class="line">        case .sunday:</span><br><span class="line">                return &quot;seventh&quot;</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>But doing the same thing twice is for lesser editors-in-chief, right? ;] Instead, take a different approach and use the <em>expression pattern</em>. First you need to overload the <em>pattern matching operator</em> in order to change its default functionality and make it work for days as well. Add the following code at the end of the playground:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">~=</span>(<span class="params">lhs</span>: <span class="type">Int</span>, <span class="params">rhs</span>: <span class="type">Day</span>)</span> -&gt; <span class="type">Bool</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> lhs <span class="operator">==</span> rhs.rawValue <span class="operator">+</span> <span class="number">1</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>This code allows you to match days to integers, in this case the numbers 1 through 7. You can use this overloaded operator to write your computed property in a different way.</p>
<p>Add the following code at the end of the playground:</p>
<p>extension Tutorial {</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> order: <span class="type">String</span> &#123;</span><br><span class="line">        <span class="keyword">guard</span> <span class="keyword">let</span> day <span class="operator">=</span> day <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&quot;not scheduled&quot;</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">switch</span> day &#123;</span><br><span class="line">        <span class="keyword">case</span> <span class="number">1</span>:</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&quot;first&quot;</span></span><br><span class="line">        <span class="keyword">case</span> <span class="number">2</span>:</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&quot;second&quot;</span></span><br><span class="line">        <span class="keyword">case</span> <span class="number">3</span>:</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&quot;third&quot;</span></span><br><span class="line">        <span class="keyword">case</span> <span class="number">4</span>:</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&quot;fourth&quot;</span></span><br><span class="line">        <span class="keyword">case</span> <span class="number">5</span>:</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&quot;fifth&quot;</span></span><br><span class="line">        <span class="keyword">case</span> <span class="number">6</span>:</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&quot;sixth&quot;</span></span><br><span class="line">        <span class="keyword">case</span> <span class="number">7</span>:</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&quot;seventh&quot;</span></span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">                <span class="built_in">fatalError</span>(<span class="string">&quot;invalid day value&quot;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">&#125;	</span><br></pre></td></tr></table></figure>


<p>Thanks to the overloaded pattern matching operator, the <code>day</code> object can now be matched to integer expressions. This is the <em>expression pattern</em> in action.</p>
<h2 id="Putting-It-All-Together"><a href="#Putting-It-All-Together" class="headerlink" title="Putting It All Together"></a>Putting It All Together</h2><p>Now that you’ve defined the day names and the tutorials’ order, you can print each tutorial’s status. Add the following block of code at the end of the playground:通过在数字上调用<code>enumberated</code>就可以像字典一样通过<code>index, tutorial</code>来遍历，如果是oc得需要先得到Index值然后再从数组里面取值，for in 可以省略这个步骤。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">NSArray *lists &#x3D; @[@(1), @(2)];</span><br><span class="line"></span><br><span class="line">for (NSNumber *item in lists) &#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line">for (int index; index&lt;lists.count; index++) &#123;</span><br><span class="line">        NSNumber *item &#x3D; lists[index];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (index, tutorial) <span class="keyword">in</span> tutorials.enumerated() &#123;</span><br><span class="line">        <span class="keyword">guard</span> <span class="keyword">let</span> day <span class="operator">=</span> tutorial.day <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="built_in">print</span>(<span class="string">&quot;<span class="subst">\(index <span class="operator">+</span> <span class="number">1</span>)</span>. <span class="subst">\(tutorial.title)</span> is not scheduled this week.&quot;</span>)</span><br><span class="line">                <span class="keyword">continue</span></span><br><span class="line">        &#125;</span><br><span class="line">                <span class="built_in">print</span>(<span class="string">&quot;<span class="subst">\(index <span class="operator">+</span> <span class="number">1</span>)</span>. <span class="subst">\(tutorial.title)</span> is scheduled on <span class="subst">\(day.name)</span>. It&#x27;s the <span class="subst">\(tutorial.order)</span> tutorial of the week.&quot;</span>)   </span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure>

<p>Notice the tuple in the <code>for-in</code> statement? There’s the <em>tuple pattern</em> again!</p>
<p>Whew! That was a lot of work for your day as editor-in-chief, but you did a fantastic job—now you can relax and kick back by the pool.</p>
<p>Just kidding! An editor-in-chief’s job is never done. Back to work!</p>
<h2 id="Where-to-Go-From-Here"><a href="#Where-to-Go-From-Here" class="headerlink" title="Where to Go From Here?"></a>Where to Go From Here?</h2><p>Here’s the final <a target="_blank" rel="noopener" href="https://koenig-media.raywenderlich.com/uploads/2016/07/patterns.playground-1.zip">playground</a>. For further experimentation, you can play around with the code in the <a target="_blank" rel="noopener" href="http://swiftlang.ng.bluemix.net/#/repl/57b2d2a68bbb01d512f4ca2b">IBM Swift Sandbox</a>.</p>
<p>If you want to read more about pattern matching in Swift, check out our <a target="_blank" rel="noopener" href="https://www.raywenderlich.com/store/swift-apprentice">Swift Apprentice</a> book and <a target="_blank" rel="noopener" href="https://twitter.com/gregheo">Greg Heo’s</a> <em>Programming in a Swift Style</em> <a target="_blank" rel="noopener" href="https://www.raywenderlich.com/132574/rwdevcon-2016-session-202-programming-swift-style-2">video</a> at <a target="_blank" rel="noopener" href="https://twitter.com/RWDevCon">RWDevCon</a> 2016.</p>
<p>I hope you find a way to use pattern matching in your own projects. If you have any questions or comments, please join the forum discussion below! :]</p>

    </div>

    
    
    
        

  <div class="followme">
    <p>Welcome to my other publishing channels</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Ray-Wenderlich/" rel="tag"># Ray Wenderlich</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2018/12/21/Swift/StackView/" rel="prev" title="UIStackView Tutorial Introducing Stack Views">
      <i class="fa fa-chevron-left"></i> UIStackView Tutorial Introducing Stack Views
    </a></div>
      <div class="post-nav-item">
    <a href="/2018/12/21/Swift/Magical%20Error%20Handling%20in%20Swift/" rel="next" title="Magical Error Handling in Swift">
      Magical Error Handling in Swift <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Getting-Started"><span class="nav-number">1.</span> <span class="nav-text">Getting Started</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Pattern-Matching-Types"><span class="nav-number">2.</span> <span class="nav-text">Pattern Matching Types</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Tuple-Pattern"><span class="nav-number">3.</span> <span class="nav-text">Tuple Pattern</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Type-Casting-Patterns"><span class="nav-number">4.</span> <span class="nav-text">Type-Casting Patterns</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Wildcard-Pattern"><span class="nav-number">5.</span> <span class="nav-text">Wildcard Pattern</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Optional-Pattern"><span class="nav-number">6.</span> <span class="nav-text">Optional Pattern</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Enumeration-Case-Pattern"><span class="nav-number">7.</span> <span class="nav-text">Enumeration Case Pattern</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Expression-Pattern"><span class="nav-number">8.</span> <span class="nav-text">Expression Pattern</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Putting-It-All-Together"><span class="nav-number">9.</span> <span class="nav-text">Putting It All Together</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Where-to-Go-From-Here"><span class="nav-number">10.</span> <span class="nav-text">Where to Go From Here?</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">HR</p>
  <div class="site-description" itemprop="description">Swimming 🏊 in the sea🌊of code!</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">38</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">9</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="mailto:caohr@outlook.com" title="E-Mail → mailto:caohr@outlook.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">HR</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a>
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
